<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="uuid" prop="name">
                    <el-input v-model="queryParams.uuid" placeholder="uuid" />
                </el-form-item>
                <el-form-item label="error_type">
                    <el-select v-model="queryParams.error_type" @change="handleQuery" clearable>
                        <el-option label="No Error" value="0" />
                        <el-option label="whisper" value="1" />
                        <el-option label="llm" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="EnvType">
                    <el-select v-model="queryParams.pk" clearable @change="handleQuery">
                        <el-option v-for="item in environmentList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- api_type筛选 -->
                <el-form-item label="api_type">
                    <el-select v-model="queryParams.api_type" clearable filterable>
                        <el-option v-for="item in apiTypeList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- audio_lang筛选 -->
                <el-form-item label="audio_lang">
                    <el-select v-model="queryParams.audio_lang" clearable filterable>
                        <el-option v-for="item in audioLangList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- note_lang筛选 -->
                <el-form-item label="note_lang">
                    <el-select v-model="queryParams.note_lang" clearable filterable>
                        <el-option v-for="item in noteLangList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- status筛选 -->
                <el-form-item label="status">
                    <el-select v-model="queryParams.status" clearable filterable>
                        <el-option v-for="item in statusList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- length区间筛选 -->
                <el-form-item label="length">
                    <el-input-number v-model="lengthRange[0]" :min="0" :max="lengthRange[1] || 99999" placeholder="最小"
                        style="width: 150px;" @change="handleLengthChange" />
                    -
                    <el-input-number v-model="lengthRange[1]" :min="lengthRange[0] || 0" :max="99999" placeholder="最大"
                        style="width: 150px;" @change="handleLengthChange" />
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        start-placeholder="开始" end-placeholder="结束" @change="timeChange" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
                    <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <div class="flex_between">
                <div></div>
                <el-button size="mini" type="danger"
                    @click="handleBatchDelete()">{{ $t('table.BatchDeletion') }}</el-button>

            </div>
            <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                <el-table-column prop="uuid" label="uuid" align="center" min-width="120" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <div style="cursor: pointer; color: blue; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; "
                            @click="
                                copyOrder1(scope.row.uuid)">
                            {{ scope.row.uuid }}
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="audio_url" label="audio_url" align="center" min-width="120"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <div style="cursor: pointer; color: blue; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; "
                            @click=" 
    copyOrder1(scope.row.audio_url)">
                            {{ scope.row.audio_url }}
                        </div>
                    </template>
                </el-table-column> -->
                <el-table-column prop="llm_title" label="llm_title" align="center" min-width="150"
                    show-overflow-tooltip>

                    <template slot-scope="scope">
                        <div style="cursor: pointer; color: blue; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; "
                            @click="
                                copyOrder1(scope.row.llm_title)">
                            {{ scope.row.llm_title }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="llm_error_info" label="llm_error_info" align="center" min-width="150"
                    show-overflow-tooltip>

                    <template slot-scope="scope">
                        <div style="cursor: pointer; color: blue; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; "
                            @click="
    copyOrder1(scope.row.llm_error_info)">
                            {{ scope.row.llm_error_info }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="whisper_result" label="whisper_result" align="center" min-width="150"
                    show-overflow-tooltip>

                    <template slot-scope="scope">
                        <div style="cursor: pointer; color: blue; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; "
                            @click="
                                copyOrder1(scope.row.whisper_result)">
                            {{ scope.row.whisper_result }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="llm_note" label="llm_note" align="center" min-width="150" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <div style="cursor: pointer; color: blue; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; "
                            @click="
                                copyOrder1(scope.row.llm_note)">
                            {{ scope.row.llm_note }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="error_type" label="error_type" align="center" min-width="90">
                    <template slot-scope="scope">
                        <el-tag v-if="!scope.row.error_type || scope.row.error_type === '0'" type="success">No
                            error</el-tag>
                        <el-tag v-else-if="scope.row.error_type === '1'" type="info">whisper</el-tag>
                        <el-tag v-else-if="scope.row.error_type === '2'" type="warning">llm</el-tag>
                        <el-tag v-else type="danger">{{ scope.row.error_type }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="api_type" label="api_type" align="center" min-width="90">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.api_type == '0'" type="info">whisper</el-tag>
                        <el-tag v-else-if="scope.row.api_type == '1'" type="danger">llm</el-tag>
                        <el-tag v-else-if="scope.row.api_type == '2'" type="success">竞品</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="length" label="length" align="center" min-width="90">
                </el-table-column>
                <el-table-column prop="audio_lang" label="audio_lang" align="center" min-width="90">
                </el-table-column>
                <el-table-column prop="note_lang" label="audio_lang" align="center" min-width="90">
                </el-table-column>
                <el-table-column prop="status" label="status" align="center" min-width="90">
                </el-table-column>
                <el-table-column prop="updated_at" label="updated_at" align="center" min-width="130"
                    show-overflow-tooltip />
                <el-table-column :label="$t('feedback.operate')" align="center" width="120">
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">{{ $t('table.delete') }}</el-button>

                    </template>

                </el-table-column>
            </el-table>


            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getMore" />
        </el-card>
    </div>
</template>

<script>
import { getApiLogNew, deleteHandel, batchDeleteHandel, getApiLogStatusList, getApiLogAudioLangList, getApiLogNoteLangList } from "@/api/ainote";
export default {
    name: "ApiLogList",
    data() {
        return {
            environmentList: [
                {
                    id: 'com.finger.AINoteTaker',
                    name: 'Production'
                },
                {
                    id: 'com.zhijian.AINoteTaker',
                    name: 'Testing'
                },
            ],
            queryParams: {
                page: 1,
                size: 10,
                error_type: "",
                uuid: '',
                pk: "com.finger.AINoteTaker",
                dateRange: { start: "", end: "" },
                api_type: "",
                audio_lang: "",
                note_lang: "",
                status: "",
            },
            lengthRange: [null, null],   // 区间筛选用，[min, max]
            tableFields: [
                "id",
                "uuid",
                "pk",
                "audio_url",
                "whisper_result",
                "llm_note",
                "error_type",
                "created_at",
                "updated_at"
            ],
            total: 0,
            loading: false,
            moreArr: [],
            dialogVisible: false,
            currentLog: {},
            value1: "",
            apiTypeList: [
                {
                    id: 0,
                    name: 'whisper'
                },
                {
                    id: 1,
                    name: 'llm'
                }
            ],
            audioLangList: [],
            noteLangList: [],
            statusList: [],
        };
    },
    methods: {
        // 绑定到长度输入控件，实时同步
        handleLengthChange() {
            if (
                this.lengthRange[0] !== null &&
                this.lengthRange[1] !== null
            ) {
                this.queryParams.length = [this.lengthRange[0], this.lengthRange[1]];
            } else {
                this.queryParams.length = undefined;
            }
        },
        copyOrder1(data1) {
            const input = document.createElement('textarea');
            input.value = data1;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        async loadDicts() {
            try {
                const [statusResp, audioLangResp, noteLangResp] = await Promise.all([
                    getApiLogStatusList(),
                    getApiLogAudioLangList(),
                    getApiLogNoteLangList()
                ]);
                this.statusList = Array.isArray(statusResp.data) ? statusResp.data : [];
                this.audioLangList = Array.isArray(audioLangResp.data) ? audioLangResp.data : [];
                this.noteLangList = Array.isArray(noteLangResp.data) ? noteLangResp.data : [];
            } catch (e) {
                this.statusList = [];
                this.audioLangList = [];
                this.noteLangList = [];
                // 可以做错误提示处理
                console.error('加载筛选字典项失败', e);
            }
        },
        async getMore() {
            if (
                this.lengthRange[0] !== null &&
                this.lengthRange[1] !== null
            ) {
                this.queryParams.length = [this.lengthRange[0], this.lengthRange[1]];
            } else {
                delete this.queryParams.length;
            }
            this.loading = true;
            try {
                let data = await getApiLogNew(this.queryParams);
                this.moreArr = data.data || [];
                this.total = data.total || 0;
            } catch (e) {
                this.$message.error("获取日志失败");
            }
            this.loading = false;
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getMore();
        },
        resetQuery() {
            this.queryParams.error_type = "";
            this.queryParams.api_type = "";
            this.queryParams.audio_lang = "";
            this.queryParams.note_lang = "";
            this.queryParams.status = "";
            this.queryParams.pk = 'com.finger.AINoteTaker';
            this.queryParams.uuid = "";
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.lengthRange = [null, null];

            this.getMore();
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1 ? this.value1[0] : null;
            this.queryParams.dateRange.end = this.value1 ? this.value1[1] : null;
            this.handleQuery();
        },
        showDetail(row) {
            this.currentLog = Object.assign({}, row);
            this.dialogVisible = true;
        },
        handleDelete(index, row) {
            this.$confirm(this.$t('review.deleteText1'), this.$t('review.deleteText2'), {
                confirmButtonText: this.$t('review.confirm'),
                cancelButtonText: this.$t('review.close'),
                type: "error",
            }).then(async () => {
                this.addLoading = true;
                this.elloading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                try {
                    await deleteHandel({ id: row.id, url: row.url });
                    this.getMore();
                    this.$message({
                        message: "success!",
                        type: "success",
                    });
                } catch (error) {
                    // 在这里可以添加错误处理逻辑
                    console.error("Error during deletion:", error);
                    this.$message({
                        message: "Failed to delete!",
                        type: "error",
                    });
                } finally {
                    this.addLoading = false;
                    this.elloading.close();

                }
            })
        },
        handleBatchDelete() {
            this.$confirm(this.$t('review.deleteText1'), this.$t('review.deleteText2'), {
                confirmButtonText: this.$t('review.confirm'),
                cancelButtonText: this.$t('review.close'),
                type: "error",
            }).then(async () => {
                this.elloading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                try {
                    let arr = this.moreArr.map(item => {
                        return {
                            id: item.id,
                            url: item.url || null
                        };
                    });
                    await batchDeleteHandel({ items: arr });

                    this.getMore();
                    this.$message({
                        message: "success!",
                        type: "success",
                    });
                } catch (error) {
                    // 在这里可以添加错误处理逻辑
                    console.error("Error during deletion:", error);
                    this.$message({
                        message: "Failed to delete!",
                        type: "error",
                    });
                } finally {
                    this.addLoading = false;
                    this.elloading.close();

                }


            });
        },
    },
    created() {
        this.getMore();
        this.loadDicts();
    }
};
</script>

<style scoped>
.boxs {
    padding: 20px;
}

.field-pair {
    margin: 10px 0;
    min-width: 200px;
}

.label {
    font-weight: bold;
    color: #666;
    display: inline-block;
    width: 110px;
}

.value {
    color: #333;
    word-break: break-all;
}
</style>
